const mongoose = require('mongoose');
const { Post, Comment, Like } = require('../db'); // 确保这里的路径正确

// 数据库连接配置
const MONGODB_URI = 'mongodb://localhost:27017/dongning'; // 请根据实际情况修改

async function connectDB() {
    try {
        await mongoose.connect(MONGODB_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        });
        console.log('✅ 数据库连接成功');
    } catch (error) {
        console.error('❌ 数据库连接失败:', error);
        process.exit(1);
    }
}

async function migrateLikesData() {
    console.log('🚀 开始迁移点赞数据...');
    let migratedCount = 0;

    try {
        const likes = await Like.find({});
        console.log(`🔍 找到了 ${likes.length} 条旧的点赞记录。`);

        for (const like of likes) {
            const { postId, commentId, openid } = like;

            if (postId) {
                // 迁移帖子点赞
                await Post.updateOne(
                    { _id: postId },
                    { $addToSet: { likedBy: openid } }
                );
                migratedCount++;
            } else if (commentId) {
                // 迁移评论点赞
                await Comment.updateOne(
                    { _id: commentId },
                    { $addToSet: { likedBy: openid } }
                );
                migratedCount++;
            }
        }

        console.log(`✅ 成功迁移了 ${migratedCount} 条点赞记录。`);

        // 验证和更新计数值
        console.log('🔄 开始同步点赞计数值...');
        const posts = await Post.find();
        for (const post of posts) {
            post.likeCount = post.likedBy.length;
            await post.save();
        }

        const comments = await Comment.find();
        for (const comment of comments) {
            comment.likeCount = comment.likedBy.length;
            await comment.save();
        }
        console.log('✅ 点赞计数值同步完成。');

    } catch (error) {
        console.error('❌ 数据迁移失败:', error);
    }
}

async function main() {
    await connectDB();
    await migrateLikesData();
    await mongoose.connection.close();
    console.log('🔌 数据库连接已关闭。');
}

main();
